//
//  YSProductDetailCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/7/22.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//  商品详情

#import "YSProductDetailCtrl.h"
#import "YSClubDataTool.h"
#import "YSProductDetailPropertyView.h"
#import "YSProductDetailBottomBar.h"
#import "AnimUtils.h"
#import "YSProdSkuView.h"
#import "CustomShowView.h"
#import "YSHomeCtrl.h"
#import "YSAccountCenterCtrl.h"
#import "YSAccountOrderStatusCtrl.h"
#import "YSOrderViewCtrl.h"
#import "YSProductNavgationShareBar.h"
#import "YSHomeDataTool.h"
#import "YSProdReviewsDetailCtrl.h"
#import "YSCommonReqTool.h"


@interface YSProductDetailCtrl ()<UIScrollViewDelegate,UIWebViewDelegate,YSProdSkuViewDelegate,YSAccountCenterDelegate,YSAccountOrderStatusDelegate,YSProductDetailPropertyViewDelegate>

@property (strong, nonatomic) UIScrollView *scrollView;
@property (assign, nonatomic) NSInteger prodId;
@property (strong, nonatomic) YSProductDetailPropertyView *headerView;
@property (strong, nonatomic) UIWebView *webView;
@property (strong, nonatomic) YSProductDetailRes *result;
@property (strong, nonatomic) YSProductDetailBottomBar *bottomBar;
@property (strong, nonatomic) UIImageView *animImage;
@property (strong, nonatomic) YSProdSkuView *skuView;
@property (strong, nonatomic) YSProductNavgationShareBar *shareBar;
@property (strong, nonatomic) UIButton *backTopBtn;
@property (strong, nonatomic) CustomShowView *showView;
@property (strong, nonatomic) UIImageView *bgHeadView;

@end

@implementation YSProductDetailCtrl

- (instancetype)initWithProdId:(NSInteger)prodId{
    self = [super init];
    if(self){
        self.prodId = prodId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     self.fd_prefersNavigationBarHidden = YES;
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self initViews];
    [self requestData];
    
    _backTopBtn = [[UIButton alloc]init];
    _backTopBtn.frame = CGRectMake(SCREENW-50, self.view.height-100, 40, 40);
    [_backTopBtn setBackgroundImage:[UIImage imageNamed:@"icon_back_top"] forState:UIControlStateNormal];
    [_backTopBtn addTarget:self action:@selector(toTop:) forControlEvents:UIControlEventTouchUpInside];
    [_backTopBtn setHidden:YES];
    [self.view insertSubview:_backTopBtn aboveSubview:self.view];
    
    NSInteger num = [DefaultsHelper integerForKey:kCartIndex];
    [self.bottomBar.cartView setNum:num];
    
    //添加一个背景头
     self.bgHeadView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg_loding_defalut"]];
    [self.bgHeadView setX:0];
    [self.bgHeadView setY:-NavWithStatusBarH];
    [self.bgHeadView setWidth:SCREENW];
    [self.view insertSubview:self.bgHeadView belowSubview:self.scrollView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSInteger num = [DefaultsHelper integerForKey:kCartIndex];
    [self.bottomBar.cartView setNum:num];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tapOpenReviewsDetail:) name:kOpenProductReviewsDetailNortif object:nil];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:kOpenProductReviewsDetailNortif object:nil];
}

-(void)tapOpenReviewsDetail:(NSNotification *)nortif{
    [self.navigationController pushViewController:[[YSProdReviewsDetailCtrl alloc]initWithProdId:_prodId] animated:YES];
}

-(void)toTop:(UIButton *)toTopBtn{
    [UIView animateWithDuration:1.0 animations:^{
        [self.webView.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    } completion:^(BOOL finished) {
        [self headerRefresh];
    }];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if([scrollView isKindOfClass:[self.webView.scrollView class]]){
        if(scrollView.contentOffset.y>SCREENH){
            [_backTopBtn setHidden:NO];
        }else{
            [_backTopBtn setHidden:YES];
        }
    }
}

-(void)initViews{
     self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH-YSProductDetailBottomBarHeight)];
    [self.scrollView setAlwaysBounceVertical:YES];
     self.scrollView.showsVerticalScrollIndicator = NO;
    [self.scrollView setDelegate:self];

    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [footer setTitle:@"上拉显示图文详情" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载图文详情..." forState:MJRefreshStatePulling];
    [footer setTitle:@"加载图文详情..." forState:MJRefreshStateRefreshing];
    // 禁止自动加载
    footer.automaticallyRefresh = NO;
    [footer setCustomArrawView:@"icon_down_arrow"];
    self.scrollView.footer = footer;
    [self.view addSubview:_scrollView];
    
    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, NavWithStatusBarH, SCREENW, SCREENH-YSProductDetailBottomBarHeight-NavWithStatusBarH)];
    [self.webView setBackgroundColor:[UIColor whiteColor]];
    self.webView.scrollView.showsVerticalScrollIndicator = NO;
    [self.webView setDelegate:self];
    [self.webView.scrollView setDelegate:self];
    [self.webView setHidden:YES];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    header.lastUpdatedTimeLabel.hidden = YES;
    [header setTitle:@"下拉商品详情" forState:MJRefreshStateIdle];
    [header setTitle:@"正在加载" forState:MJRefreshStatePulling];
    [header setTitle:@"下拉商品详情..." forState:MJRefreshStateRefreshing];
    self.webView.scrollView.header =  header;
     header.lastUpdatedTimeLabel.hidden = YES;
    [header setCustomArrawView:@"icon_down_arrow"];
    [self.view addSubview:_webView];
    
    self.bottomBar = [YSProductDetailBottomBar bottomBar];
    [self.bottomBar setWidth:SCREENW];
    [self.bottomBar setX:0];
    [self.bottomBar setY:SCREENH-self.bottomBar.height];
    
    __weak YSProductDetailCtrl *ctrl = self;
    [self.bottomBar setAddCart:^{
        [ctrl addProdToCart];
    }];
    [self.bottomBar setImmediateBuy:^{
        [ctrl immediateBuy];
    }];
    [self.view addSubview:self.bottomBar];
    
    
    _shareBar = [YSProductNavgationShareBar shareBar];
    [_shareBar setWidth:SCREENW];
    [_shareBar.rightBtn setBackgroundImage:[UIImage imageNamed:@"tabar_collect_normal"] forState:UIControlStateNormal];
    [_shareBar.rightBtn setBackgroundImage:[UIImage imageNamed:@"tabar_collect_press"] forState:UIControlStateHighlighted];
    [_shareBar.rightBtn setBackgroundImage:[UIImage imageNamed:@"tabar_collect_press"] forState:UIControlStateSelected];
    [_shareBar.rightBtn addTarget:self action:@selector(tapMark:) forControlEvents:UIControlEventTouchUpInside];
    [_shareBar setX:0];
    [_shareBar setY:0];
    [self.view addSubview:_shareBar];
}

/**
 *  加入购物篮按钮点击
 */
-(void)addProdToCart{
     _skuView.type = NO;
    [_skuView.calcView setNum:1];
    // 首选判断是否有一个选中
    if([_skuView hasOneChecked]&&_result.prodSub.count<=1){
        [self buyBtnClickWtihCount:[_skuView.calcView getNum] type:NO];
    }else{
        //滑出sku页面
        if(!_showView){
            CustomShowView *showView = [[CustomShowView alloc]initWithCustomView:_skuView location:CustomShowViewLocationBottomType];
            _showView = showView;
        }
        [_showView showWithAnim:YES];
    }
}

/**
 *  立即购买按钮点击
 */
-(void)immediateBuy{
    _skuView.type = YES;
    [_skuView.calcView setNum:1];
    if(!_showView){
        CustomShowView *showView = [[CustomShowView alloc]initWithCustomView:_skuView location:CustomShowViewLocationBottomType];
        _showView = showView;
    }
    [_showView showWithAnim:YES];
}

/**
 *  选择规格点击
 */
-(void)tapOpenSku{
    _skuView.type = NO;
    [_skuView.calcView setNum:1];
    if(!_showView){
        CustomShowView *showView = [[CustomShowView alloc]initWithCustomView:_skuView location:CustomShowViewLocationBottomType];
        _showView = showView;
    }
    [_showView showWithAnim:YES];
}

-(void)startShopCartAnim{
    //执行加入购物篮动画.动画执行完毕更新购物篮数量图标
    NSInteger tag = _result.prodImages.count>1?1001:1000;
    UIImage *image = ((UIImageView *)[self.headerView.bannerView viewWithTag:tag]).image;
    if (image==nil) {
        image = [UIImage imageNamed:@"ic_launcher"];
    }
    _animImage = [[UIImageView alloc]initWithImage:image];
    _animImage.size = CGSizeMake(SCREENW/2, SCREENW/2);
    [_animImage.layer setCornerRadius:SCREENW/4];
    _animImage.layer.masksToBounds = YES;
    _animImage.center = self.headerView.center;
    [self.view addSubview:_animImage];
    [AnimUtils addToCartAnim:_animImage startView:self.headerView.bannerView endView:self.bottomBar.cartView delegate:self adverse:1];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    [self.animImage removeFromSuperview];
    
     //更新购物篮图标
    if(ISLOGIN){
        __weak typeof (self) weakSelf = self;
        [[YSCommonReqTool sharedTool] loadIndex:YSBadgeCartType callback:^(NSInteger count) {
            [weakSelf.bottomBar.cartView setNum:count];
        }];
    }else{
        [DefaultsHelper setInteger:0 forKey:kCartIndex];
    }
}

-(void)headerRefresh{
    [self.webView.scrollView.header endRefreshing];
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self.webView setHidden:YES];
    [UIView animateWithDuration:0.5 animations:^{
        [self.shareBar setAlpha:1.0];
        [self.shareBar setBackgroundColor:[UIColor clearColor]];
    }];
}

-(void)footerRefresh{
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_result.prodDetailUrl]]];
    [UIView animateWithDuration:0.5 animations:^{
        [self.shareBar setAlpha:0.9];
         [self.shareBar setBackgroundColor:[UIColor whiteColor]];
    }];
    
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    [self.scrollView.footer endRefreshing];
    CGSize actualSize = [webView sizeThatFits:CGSizeZero];
    self.webView.scrollView.contentSize = actualSize;
    [self.webView setHidden:NO];
}

-(void)requestData{
    BOOL isLogin = NO;
    if (ISLOGIN) {
        isLogin = YES;
    }
    [YSClubDataTool getProductDetail:_prodId isLogin:isLogin success:^(YSProductDetailRes *result) {
        if(result.isSucc){
            [self inflateData:result];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure);
    }];
}

-(void)inflateData:(YSProductDetailRes *)result{
    _result = result;
    self.headerView = [[YSProductDetailPropertyView alloc]init];
    [self.headerView setResult:result];
    [self.headerView setDelegate:self];
    [self.headerView setX:0];
    [self.headerView setY:0];
    
    [self.scrollView addSubview:self.headerView];
    [self.scrollView setContentSize:CGSizeMake(SCREENW, self.headerView.height)];
    
    //mark
    if(result.isMark == 1)
        [self.shareBar.rightBtn setSelected:YES];
    else
        [self.shareBar.rightBtn setSelected:NO];
    //iscanbuy
    if([result isCanBuy] == 1){
            [self.bottomBar.immediateBuyBtn setEnabled:YES];
            [self.bottomBar.addCartBtn setEnabled:YES];
    }else{
            [self.bottomBar.immediateBuyBtn setEnabled:NO];
            [self.bottomBar.addCartBtn setEnabled:NO];
    }
    YSShareModel *sm = [YSShareModel new];
    [sm setUrl:_result.shareLinks];
    [sm setTitle:_result.prodName];
    [sm setSubTile:_result.prodSellingPoint];
    if(_result.prodImages.count){
        [sm setImageUrl:_result.prodImages[0]];
    }
    [_shareBar setShareModel:sm];
    
    if(result.volume){//是否是团购券
        [self.bottomBar.addCartBtn setHidden:YES];
    }else{
        [self.bottomBar.addCartBtn setHidden:NO];
    }
    
    //设置sku与图文详情
    _skuView = [[YSProdSkuView alloc]initWithProdDetail:result];
    [_skuView setDelegate:self];
}

-(void)tapMark:(UIButton *)sender{
    if(ISLOGIN){
        NSInteger isMark = self.shareBar.rightBtn.isSelected == YES?ResultFailureType:ResultSuccessType;
        [YSClubDataTool markProductWithProdId:[NSString stringWithFormat:@"%ld",_result.prodId] isMark:isMark success:^(BaseResponse *result) {
            if(result.isSucc){
                if(isMark == ResultSuccessType){
                    [self.shareBar.rightBtn setSelected:YES];
                    ShowTips(@"收藏成功")
                }else{
                    [self.shareBar.rightBtn setSelected:NO];
                    ShowTips(@"已取消收藏")
                }
            }else{
               ShowEnterTips(result.data);
            }
        } failure:^(NSError *error) {
            ShowTips(kRequestFailure)
        }];
    }else{
        [Utils showLoginCtrl:self];
    }
}

/**
 *  SKU里面的btn点击
 *
 *  @param count
 *  @param type 是否是直接购买，yes直接跳转到结算中心，否则加入购物篮
 */
- (void)buyBtnClickWtihCount:(NSUInteger)count type:(BOOL)type{
    NSLog(@"SKU里面的btn点击");
    if (ISLOGIN) {
        YSSubProduct *subProd =  _result.prodSub[[_skuView getSelectIndex]];
        [YSClubDataTool addCartWithParam:subProd.prodSubId prodCount:count type:type==YES?0:1 success:^(BaseResponse *result) {
            if(result.isSucc){
                if(!_showView){
                    CustomShowView *showView = [[CustomShowView alloc]initWithCustomView:_skuView location:CustomShowViewLocationBottomType];
                    _showView = showView;
                }
                [_showView hideWithAnim:YES];
                if(type){//立即购买，跳转到结算中心
                //判断是否是体验券
                 AccountCenterProductType prodcutType =
                    _result.volume == 1
                    ?experienceProductType
                    :ordinaryProductType;
                   
                   YSAccountCenterCtrl *ctrl =  [[YSAccountCenterCtrl alloc]initWithOrdreCode:nil selectProdIds:[NSString stringWithFormat:@"%ld",subProd.prodSubId] targetType:accountCenterFinishProductDetailType productType:prodcutType];
                    [ctrl setDelegate:self];
                    [self.navigationController pushViewController:ctrl animated:YES];
                }else{
                  [self startShopCartAnim];
                }
            }else{
                ShowEnterTips(result.data);
            }
        } failure:^(NSError *error) {
            ShowTips(kRequestFailure);
        }];
    }else{
        if([_showView isShowing]){
            [_showView hideWithAnim:YES];
        }
        [Utils showLoginCtrl:self];
    }
}

/**
 *  结算中心页面关闭回调
 *
 *  @param type
 *  @param status
 */
-(void)accountCenterFinish:(int)type status:(NSString *)status{
    if(type == accountCenterFinishProductDetailType){
        [self toOrderStatusPage:status];
    }
}

/**
 *  跳转至支付状态页面
 *
 *  @param resultCode 状态码
 */
-(void)toOrderStatusPage:(NSString *)resultCode
{
    YSAccountOrderStatusCtrl *ctr = [YSAccountOrderStatusCtrl initWithResultCode:resultCode targetType:orderStatusFinishProductDetailType];
    ctr.delegate = self;
    //进入状态页面
    [self.navigationController pushViewController:ctr  animated:YES];
}

/**
 *  订单状态页面关闭,回调跳转至订单列表页
 *
 *  @param type
 */
-(void)orderStatusFinish:(int)type
{
    if(orderStatusFinishProductDetailType == type){
        CustomNavigationCtrl *nav = [[CustomNavigationCtrl alloc]initWithRootViewController:[YSOrderViewCtrl new]];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    }
}

-(void)dealloc{
    self.webView.delegate = nil;
    [self.webView stopLoading];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end
